import React, { Fragment, PropsWithChildren, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { trimPath, filterPermission } from "./checkPermission";

interface AuthorizedProps {
  currentPath: string,
  checkLogin: () => Promise<boolean>,
  noLoginRedirectPath: string,
  noVerifyLoginPathList: string[],
}

const Authorized: React.FC<PropsWithChildren<AuthorizedProps>> = ({ currentPath, checkLogin, noLoginRedirectPath, noVerifyLoginPathList, children }) => {
  const navigate = useNavigate();
  useEffect(() => {
    if (checkLogin && !noVerifyLoginPathList.includes(trimPath(currentPath))) {
      checkLogin()
        .then(() => { })
        .catch(() => {
          if (!noLoginRedirectPath) return console.warn("未设置noLoginRedirectPath的值");
          navigate(noLoginRedirectPath, { replace: true })
        })
    }
  }, []);

  return (
    <Fragment>{children}</Fragment>
  )
}

export { filterPermission, trimPath };

export default Authorized;
